#!/usr/bin/env python
"""
DatabaseMgr.py

Handle database functions. If the user has the corresponding db
configured, we wire it into the menu.
"""

def _(s): return s

import wx
import frontend.mainWindow.MenuHandler as MenuHandler
from settings import UserSettings

class DatabaseMgr:
    _shared_state = {}
    
    def __init__(self):
        self.__dict__ = _shared_state
        if not hasattr(self, "lookupTbl"):
            setState()
    
    def setState(self):
        self.lookupTbl = {
                         "db2":(_("DB2"), self.OnDB2),
                         "firebird":(_("Firebird"), self.OnFirebird),
                         "mysql":(_("MySQL"), self.OnMysql),
                         "oracle":(_("Oracle"), self.OnOracle),
                         "postgresql":(_("PostgreSQL"), self.OnPostgresql),
                         }
        dbs = UserSettings.UserSettings().databaseList()
        self.currDBs = [db for db in dbs if db in self.lookupTbl]
        self.menu = MenuHandler.MenuHandler()
        self.ids = set()
        self.doMenu()
        return self
    
    def numDBs(self):
        return len(self.currDBs)
    
    def dbNameTuples(self):
        li = [(self.lookupTbl[db][0], db) for db in self.currDBs]
        li.sort()
        return li
    
    def addDBs(self, dbs):
        for db in dbs:
            if db not in self.currDBs:
                self.currDBs.append(db)
    
    def removeDBs(self, dbs):
        for db in dbs:
            if db in self.currDBs:
                self.currDBs.remove(db)
    
    def doMenu(self):
        #self.menu.difference_update(self.ids)
        for id in set(self.ids):
            self.menu.Remove(id[0])
        self.ids.clear()
        i = 1
        for (name, fct) in self.dbNameTuples():
            id = wx.NewId()
            menutxt = _("&%s %s") % (i, name)
            i += 1
            sbtxt = _("Configure %s database") % name
           # e = self.menu.Append(id, menutxt, sbtxt)
           # self.ids.add((id, 0))
            #self.Bind(wx.EVT_MENU, fct, e)
       # menuInfo.update(self.ids)
    
#    def addto(instance):
#        def decorator(f):
#            import new
#            f = new.instancemethod(f, instance, instance.__class__)
#            setattr(instance, f.func_name, f)
#            return f
#        return decorator
    
    def OnDB2(self, evt):
        print "OnDB2"
        pass
    
    def OnFirebird(self, evt):
        print "OnFirebird"
        pass
    
    def OnMysql(self, evt):
        print "OnMysql"
        pass
    
    def OnOracle(self, evt):
        print "OnOracle"
        pass
    
    def OnPostgresql(self, evt):
        print "OnPostgresql"
        pass
    
